// 实际意义上的FileWriterWrapper
package object

import (
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
	"math/rand"
	"time"
	"xj.com/oos-data-service/config"
	"xj.com/oos-data-service/dto"
	"xj.com/oos-data-service/error_handler"
	"xj.com/oos-data-service/service/elasticsearch"
	"xj.com/oos-data-service/service/file"
)

type ObjectService struct {
	elasticsearchService *elasticsearch.ElasticsearchService
	fileServices         []*file.FileService
}

func New() (s *ObjectService) {
	s = new(ObjectService)

	log.Info("初始化数据写入的协程...")
	writers := len(config.Config.Writers)
	log.Info("共：", writers, "个协程。")
	if writers == 0 {
		error_handler.ExitWenError(errors.New("未定义文件写入线程。请先配置writer。"))
	}
	//启动各个writer
	for _, writer := range config.Config.Writers {
		fileService := file.New(writer.Dir, writer.WorkFileSize)
		s.fileServices = append(s.fileServices, fileService)
	}
	s.elasticsearchService = elasticsearch.New()
	return s
}

func (s *ObjectService) Upload(objectId string, createTime time.Time, payload []byte) error {
	errorChan := make(chan error, 1)
	fileInfo := dto.FileInfo{
		ObjectId:   objectId,
		CreateTime: createTime,
		Payload:    payload,
		ErrorChan:  errorChan,
	}

	metaInfo := s.getFileService().Write(fileInfo)
	s.elasticsearchService.WriteMetaInfo(metaInfo)

	return nil
}

func (s *ObjectService) Get(objectId string) []byte {
	metaInfo := s.elasticsearchService.GetMetaInfo(objectId)
	return s.getFileService().Read(metaInfo)
}

func (s *ObjectService) getFileService() *file.FileService {
	i := rand.Intn(len(config.Config.Writers))
	return s.fileServices[i]
}
